package com.fy.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fy.core.consts.ExamContant;
import com.fy.core.context.AuthContext;
import com.fy.core.enums.ApiErrorEnum;
import com.fy.core.exception.ServiceException;
import com.fy.core.vo.ApiRest;
import com.fy.exam.dto.ExamCreateDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.core.dto.PageDto;
import com.fy.core.vo.PageResult;
import com.fy.exam.entity.*;
import com.fy.exam.mapper.ExamDepartMapper;
import com.fy.exam.entity.ExamDepart;
import com.fy.exam.mapper.ExamMapper;
import com.fy.exam.mapper.ExamRepoMapper;
import com.fy.exam.mapper.ExamUserMapper;
import com.fy.exam.service.ExamService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author
 * @since 2023-06-14
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {
    @Autowired
    private ExamRepoMapper examRepoMapper;
    @Autowired
    private ExamDepartMapper examDepartMapper;
    @Autowired
    private ExamUserMapper examUserMapper;
    @Autowired
    private ExamMapper examMapper;

    @Override
    public ApiRest save(ExamCreateDto examCreateDto) {
        /*1.参数校验*/
        checkData(examCreateDto);
        /*2.保存exam*/
        Exam exam = new Exam();
        BeanUtil.copyProperties(examCreateDto, exam, true);
        if (examCreateDto.getId() == null) {
            exam.setId(IdWorker.getIdStr());
            exam.setCreateTime(new Date());
        } else {
            exam.setId(examCreateDto.getId());
        }
        exam.setUpdateTime(new Date());
        exam.setJoinType(ExamContant.ZUJUAN_REPO);
        exam.setLevel(ExamContant.LEVEL_PUTONG);
        exam.setState(ExamContant.CREATE);
        this.baseMapper.insert(exam);
        /*3.保存exam_repo*/
        examCreateDto.getExamRepos().forEach(examRepo -> {
            examRepo.setId(IdWorker.getIdStr());
            examRepo.setExamId(exam.getId());
            examRepoMapper.insert(examRepo);
        });

        /*4.exam_depart*/
        if (examCreateDto.getOpenType() == ExamContant.OPENT_DEPART) {
            examCreateDto.getDepartIds().forEach(departId -> {
                ExamDepart examDepart = new ExamDepart();
                examDepart.setExamId(exam.getId());
                examDepart.setId(IdWorker.getIdStr());
                examDepart.setDepartId(departId);
                examDepartMapper.insert(examDepart);
            });
        }
        /*5.exam_user*/
        if (examCreateDto.getOpenType() == ExamContant.OPENT_SPECIFY) {
            examCreateDto.getUserIds().forEach(userId -> {
                ExamUser examUser = new ExamUser();
                examUser.setExamId(exam.getId());
                examUser.setId(IdWorker.getIdStr());
                examUser.setExamId(userId);
                examUserMapper.insert(examUser);
            });
        }
        log.info("{}创建了{}考试", new Date(), examCreateDto.getTitle());
        return ApiRest.success("创建考试成功", "");
    }

    @Override
    public ApiRest findByExamId(String examId) {
        ExamCreateDto examCreateDto = new ExamCreateDto();
        Exam exam = this.baseMapper.selectById(examId);
        BeanUtil.copyProperties(exam,examCreateDto,true);
        //获取examRepos
        QueryWrapper<ExamRepo> examRepoQueryWrapper = new QueryWrapper<>();
        examRepoQueryWrapper.lambda().eq(ExamRepo::getExamId, examId);
        List<ExamRepo> examRepos = examRepoMapper.selectList(examRepoQueryWrapper);
        examCreateDto.setExamRepos(examRepos);
        System.out.println("examRepos = " + examRepos);

        //获取departIds
        QueryWrapper<ExamDepart> examDepartQueryWrapper = new QueryWrapper<>();
        examDepartQueryWrapper.lambda().eq(ExamDepart::getExamId, examId);
        List<ExamDepart> examDeparts = examDepartMapper.selectList(examDepartQueryWrapper);
        List<String> departIds = new ArrayList<>();
        for (ExamDepart examDepart : examDeparts) {
            departIds.add(examDepart.getDepartId());
        }
        examCreateDto.setDepartIds(departIds);

        //获取userIds
        QueryWrapper<ExamUser> examUserQueryWrapper = new QueryWrapper<>();
        examUserQueryWrapper.lambda().eq(ExamUser::getUserId, examId);
        List<ExamUser> examUsers = examUserMapper.selectList(examUserQueryWrapper);
        List<String> userIds = new ArrayList<>();
        for (ExamUser examUser : examUsers) {
            userIds.add(examUser.getUserId());
        }
       examCreateDto.setUserIds(userIds);

        return ApiRest.success(examCreateDto);
    }

    @Override
    @Transactional
    public ApiRest update(ExamCreateDto examCreateDto) {
        deleteExam(examCreateDto.getId());
        save(examCreateDto);
        return ApiRest.success("修改成功");
    }

    @Override
    public ApiRest deleteExam(String examId) {

        //删除: el_exam
        examMapper.deleteById(examId);

        //删除: el_exam_depart
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("exam_id", examId);
        examDepartMapper.delete(updateWrapper);
        //删除: el_exam_repo
        examRepoMapper.delete(updateWrapper);

        //删除: el_exam_user
        examUserMapper.delete(updateWrapper);

        return ApiRest.success("考试删除成功！", "");
    }

    public ApiRest batchDelete(List<Exam> exams) {
        for (Exam exam : exams) {
            deleteExam(exam.getId());
        }
        return ApiRest.success("批量删除成功！", "");
    }

    @Override
    public PageResult<Exam> findPage(PageDto<Exam> pageDto) {
        //分页信息
        IPage<Exam> page = new Page<>(pageDto.getNow(), pageDto.getSize());

        //条件
        Exam where = pageDto.getWhere();
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(where.getOpenType())) {
            queryWrapper.lambda().eq(Exam::getOpenType, where.getOpenType());
        }
        if (!StringUtils.isEmpty(where.getStartTime())) {
            queryWrapper.lambda().eq(Exam::getStartTime, where.getStartTime());
        }
        if (!StringUtils.isEmpty(where.getEndTime())) {
            queryWrapper.lambda().eq(Exam::getEndTime, where.getEndTime());
        }
        if (!StringUtils.isEmpty(where.getTitle())) {
            queryWrapper.lambda().like(Exam::getTitle, where.getTitle());
        }

        //开查
        IPage<Exam> pageInfo = this.baseMapper.selectPage(page, queryWrapper);

        PageResult<Exam> pageResult = new PageResult<>();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());
        return pageResult;


    }

    @Override
    public ApiRest<List<Exam>> selectMyExams() {
        System.out.println("+++++++"+AuthContext.getUser());

        Long userId = AuthContext.getUser().getUserId();
        System.out.println("userId = " + userId);
        List<Exam> examList = this.baseMapper.findMyExam(userId+"");

        return ApiRest.success(examList);
    }

    /**
     * 参数校验
     *
     * @param examCreateDto
     */
    private void checkData(ExamCreateDto examCreateDto) {
        System.out.println(examCreateDto);
        /*参数不能为空*/
        if (examCreateDto == null) {
            throw new ServiceException(ApiErrorEnum.PARAM_SHOULD_NOT_NULL);
        }
        /*考试名称不能为空*/
        if (StringUtils.isEmpty(examCreateDto.getTitle())) {
            throw new ServiceException(ApiErrorEnum.EXAM_CONTENT_IS_NULL);
        }
        /*未绑定题库*/
        if (CollectionUtils.isEmpty(examCreateDto.getExamRepos())) {
            throw new ServiceException(ApiErrorEnum.EXAM_REPO_IS_NULL);
        }
        /*考试时长未设置*/
        if (StringUtils.isEmpty(examCreateDto.getTotalTime())) {
            throw new ServiceException(ApiErrorEnum.EXAM_TOTAL_TIME);
        }
        /*及格分未设置*/
        if (StringUtils.isEmpty(examCreateDto.getQualifyScore())) {
            throw new ServiceException(ApiErrorEnum.EXAM_QUALIFY_SCORE);
        }

    }
}
